package main

/**
* @Author: DengLibin
* @Date: Create in 2023-01-10 14:03:50
* @Description:
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
*/

type ListNode struct {
	Val  int
	Next *ListNode
}

/**
 * @Author: DengLibin
 * @Date: Create in 2023-01-10 14:05:03
 * @Description: 有序链表合并 双指针法
 */
func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode {
	if list1 == nil {
		return list2
	}
	if list2 == nil {
		return list1
	}

	tmpNode1 := list1
	tmpNode2 := list2
	var head *ListNode = nil
	if tmpNode1.Val <= tmpNode2.Val {
		head = tmpNode1
		tmpNode1 = tmpNode1.Next
	} else {
		head = tmpNode2
		tmpNode2 = tmpNode2.Next
	}
	var current = head

	for tmpNode1 != nil && tmpNode2 != nil {
		if tmpNode1.Val <= tmpNode2.Val {
			current.Next = tmpNode1
			tmpNode1 = tmpNode1.Next
		} else {
			current.Next = tmpNode2
			tmpNode2 = tmpNode2.Next
		}
		current = current.Next

	}

	if tmpNode1 != nil {
		current.Next = tmpNode1
	}
	if tmpNode2 != nil {
		current.Next = tmpNode2
	}

	return head
}
